/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.lang;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public class NamedThreadFactory implements ThreadFactory {

    private final boolean single;
    private final String namePrefix;
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    public NamedThreadFactory(String namePrefix) {
        this(namePrefix, false);
    }

    public NamedThreadFactory(String namePrefix, boolean single) {
        Checks.verifyNotNull(namePrefix, "namePrefix");
        this.single = single;
        this.namePrefix = namePrefix;
        SecurityManager s = System.getSecurityManager();
        this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable runnable) {
        String threadName;
        if (single) {
            threadName = namePrefix;
        } else {
            threadName = namePrefix + threadNumber.getAndIncrement();
        }
        Thread thread = new Thread(group, runnable, threadName, 0);
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }

    public static ThreadFactory pool(String namePrefix) {
        return new NamedThreadFactory(namePrefix);
    }

    public static ThreadFactory single(String threadName) {
        Checks.verifyNotNull(threadName, "threadName");
        return new NamedThreadFactory(threadName, true);
    }
}
